import { defineStore } from "pinia";
import { loginApi, getUserInfoApi, getMenuApi } from "../../api/user.js";
const userStore = defineStore("user", {
  state: () => ({
    token: localStorage.getItem("token") || "",
    user: localStorage.getItem("user") || "",
    menu: [],
    user_pic: localStorage.getItem("user_pic") || "",
  }),
  actions: {
    // 登录
    async loginuser(data) {
      try {
        let response = await loginApi(data);
        if (response.code === 200) {
          console.log(response.data);
          this.user = response.data;
          // 保存token到localStorage
          if (response.data.token) {
            localStorage.setItem("token", response.data.token);
            console.log("✅ Token saved to localStorage");
          } else if (response.data.data && response.data.data.token) {
            localStorage.setItem("token", response.data.data.token);
            console.log("✅ Token saved to localStorage from nested data");
          }
          return true;
        } else {
          console.log("登录失败");
          return false;
        }
      } catch (error) {
        console.error("登录异常:", error);
        return false;
      }
    },
    // 获取用户信息
    async userUserInf() {
      let res = await getUserInfoApi();
      if (res.code === 200) {
        this.user = res.data;
        console.log(this.user);
        localStorage.setItem("user", JSON.stringify(res.data.username));
        localStorage.setItem("user_pic", JSON.stringify(res.data.user_pic));
        return true;
      } else {
        console.log("获取用户信息失败");
        return false;
      }
    },
//获取菜单
    async getMenu() {
      let menu = await getMenuApi();
      if (menu.code === 200) {
        this.menu = menu.data;
        console.log(menu, this.menu);
        return true;
      } else {
        console.log("获取菜单失败");
        return false;
      }
    },
  },
});

export default userStore;
